import { H3Event } from 'h3'
import { getUserPersonInfo } from '~/service/yapi'
import jwt from 'jsonwebtoken';
export const SECRET = process.env.JWT_SECRET 

const TOKEN_TYPE = 'Bearer'

const extractToken = (authHeaderValue: string) => {
  const [, token] = authHeaderValue.split(`${TOKEN_TYPE} `)
  return token
}

const ensureAuth = async (event: H3Event) => {
  const authHeaderValue = getRequestHeader(event, 'authorization')
  if (typeof authHeaderValue === 'undefined') {
    throw createError({ statusCode: 403, statusMessage: 'Need to pass valid Bearer-authorization header to access this endpoint' })
  }

  const extractedToken = extractToken(authHeaderValue)
  let userRes: any = await getUserPersonInfo({}, extractedToken)
  let expiresIn = 30 * 24 * 60 * 60;
  const nuxtAccessToken = jwt.sign({ ...userRes.data, scope: ['user'] }, SECRET, { expiresIn })
  return nuxtAccessToken

}
type SessionData = {
  id: string
  username: string
  nickname: string
  realname: string
  avatar: string
  labels: string
  phone: string
  beInvitedCode: string
  inviteCode: string
  PythonCourseVIP: string
  score: number
  challengeVIP: number
  isCheckIn: boolean
  goodsUrl: string
  userGoods: [any]
}
export default eventHandler(async (event: any) => {
  const user: SessionData = await ensureAuth(event)
  return user
})
